<template>
  <div style="height:100%" id="app">

    <router-view v-if="!!isShow" :page="pageConfig" :host="host">

    </router-view>

    <CircleMenu v-if="($route.path=='/signup'||
    $route.path=='/disclaimer'||
    $route.path=='/list'||
    $route.path=='/certificate/identity'||
    $route.path=='/certificate/number'||
    $route.path=='/form'||
    $route.path=='/certificate/createteam'||
    $route.path=='/teamlist'||
    $route.path=='/certificate/number'||$route.path=='createteam')&&pageType!='baoming'
    "></CircleMenu>

    <!--登录模态框-->
    <div id='showlogin' v-transfer-dom>
      <x-dialog hide-on-blur v-model="showToast" class="dialog-demo">

        <div v-show='mode==""' style="padding:15px;">
          <div>登录/注册</div>
          <group title="">
            <x-input :debounce="1500" @on-change="usernameChange" placeholder="手机号" v-model="username"></x-input>

            <x-input v-show='state=="login"' v-model="loginPsword" type="password" placeholder='密码'></x-input>
            <div v-show='state=="reg"' class="l-captcha" data-callback='getResponse' data-site-key="0a619586b48d74f0b45f48998df51754"></div>
            <x-input v-show='state=="reg"' placeholder="请填写验证码" v-model="regCode" class="weui-vcode">
              <x-button style="padding: 0 0.5em;" :disabled='clock' slot="right" type="primary" @click.native="countDown('reg')" mini>{{codeMessage}}
              </x-button>
            </x-input>
            <x-input v-show='state=="reg"' v-model="regPsword" type="password" placeholder='注册密码'></x-input>

          </group>
          <div v-show='state=="login"' style="text-align: left;padding-left: 15px;padding-top: 15px;" @click='show("pwd")'>
            <i class="fa fa-question-circle-o"></i>忘记密码</div>

          <group v-show='state==""' title="">

            <x-button type='primary' @click.native='usernameChange' text='下一步'></x-button>
          </group>
          <group v-show='state=="reg"' title="">
            <x-button type='primary' @click.native="reg" text='注册'></x-button>
          </group>

          <group v-show='state=="login"' title="">
            <x-button type='primary' @click.native="login" text='登录'></x-button>
          </group>
          <div class="icons">
            <span @click='show("wxlogin")'>
              <i class="fa fa-weixin"></i>微信登录</span>
            <span @click='show("codelogin")'>
              <i class="fa fa-comments"></i>验证码登录</span>

          </div>
        </div>

        <div v-show='mode=="codelogin"' style="padding:15px;">

          <div>验证码登录</div>
          <group title="">
            <x-input :debounce="1500" @on-change="codeChange" v-model="codeusername" placeholder="手机号"></x-input>

            <div class="l-captcha" data-callback='getResponse' data-site-key="0a619586b48d74f0b45f48998df51754"></div>
            <x-input placeholder="请填写验证码" v-model="code" class="weui-vcode">
              <x-button style="padding: 0 0.5em;" :disabled='clock' slot="right" type="primary" @click.native="countDown('login')" mini>{{codeMessage}}
              </x-button>
            </x-input>

          </group>

          <group title="">
            <x-button type='primary' @click.native="codelogin" text='登录'></x-button>
          </group>
          <div class="icons">
            <span @click='show("wxlogin")'>
              <i class="fa fa-weixin"></i>微信登录</span>
            <span @click='show("")'>
              <i class="fa fa-comments"></i>密码登录</span>
          </div>
        </div>

        <div v-show='mode=="pwd"' style="padding:15px;">
          <div>忘记密码</div>
          <group title="">
            <x-input :debounce="1500" @on-change="codeChange" v-model="forusername" placeholder="手机号"></x-input>

            <div class="l-captcha" data-callback='getResponse' data-site-key="0a619586b48d74f0b45f48998df51754"></div>
            <x-input placeholder="请填写验证码" v-model="code" class="weui-vcode">
              <x-button style="padding: 0 0.5em;" :disabled='clock' slot="right" type="primary" @click.native="countDown('forgetpass')" mini>{{codeMessage}}
              </x-button>
            </x-input>

            <x-input v-model="forgetPsword" type="password" placeholder='新密码'></x-input>

          </group>

          <group title="">
            <x-button type='primary' @click.native="forget" text='提交'></x-button>
          </group>
          <div class="icons">
            <span @click='show("wxlogin")'>
              <i class="fa fa-weixin"></i>微信登录</span>
            <span @click='show("")'>
              <i class="fa fa-comments"></i>密码登录</span>
          </div>

        </div>

        <!-- <div @click="showToast=false">
          <span class="vux-close"></span>
        </div> -->
      </x-dialog>
    </div>

    <div>

    </div>

    <!-- <CircleMenu1></CircleMenu1> -->

    <!-- <myFooter :page="pageConfig"></myFooter> -->
  </div>
</template>



<script>
const countTime = 60; //倒数计时60秒

import VConsole from "vconsole/dist/vconsole.min.js";
import { cookie } from "vux";
import Vue from "vue";
/* eslint-disable*/
import "babel-polyfill";
import { axios } from "@/api/axios.js";
import qs from "qs";

import { isIdNumber, isTel, setTitle } from "@/common/js/main.js";

//小程序的按钮
import CircleMenu from "@/common/components/mycirclemenu.vue";
//报名页面的按钮
import CircleMenu1 from "@/common/components/mycirclemenu1.vue";

import { ConfigPlugin } from "vux";
import { XDialog, XButton, Group, Cell, XInput } from "vux";
Vue.use(ConfigPlugin, {
  $layout: "VIEW_BOX"
});

import { TransferDomDirective as TransferDom } from "vux";

import { Toast } from "vux";
import myFooter from "@/common/components/myfooter";
import { querystring } from "vux";

import Bus from "@/common/js/bus.js";

import { host } from "@/api/config.js";
import { raceShow } from "@/api/raceshow.js";

import { GetQueryString, hostoperating } from "@/common/js/main.js";
import { setTimeout } from "timers";

export default {
  name: "app",
  data() {
    return {
      forusername: "",
      codeusername: "",
      forgetPsword: "",
      regCode: "",
      regPsword: "",
      regPsword2: "",
      code: "",
      mode: "", //'':注册/登录 wx:微信登录 code:验证码登录
      loginPsword: "",
      state: "",
      clock: false, //验证码状态锁
      codeMessage: "发送验证码", //验证码倒数数字
      username: "",
      showToast: false,
      isShow: false,
      pageConfig: window.pageConfig,
      host: "",
      _captcha_: ""
    };
  },
  directives: {
    TransferDom
  },
  watch: {
    $route(to, from) {
      //alert(from.path)
      //alert(to.path)
      if (
        from.path == "/list" ||
        (from.path == "/" && to.path == "/disclaimer")
      ) {
        //alert(window.localStorage.getItem("disclaimerID") === "null")
        if (window.localStorage.getItem("disclaimerID") === "null") {
          this.$router.push("./certificate/identity");
        }
      }
    }
  },
  created() {
    //打开控制台
    //let vConsole = new VConsole();

    //清楚缓存设置
    window.localStorage.setItem("isTeam", "fasle");

    //控制raceid
    if (
      !/\/\d*#/.exec(window.location.href) ||
      /\/\d*#/.exec(window.location.href)[0] == "/#"
    ) {
    } else {
      var raceid = /\/\d*#/.exec(window.location.href)[0];
      raceid = raceid.replace(/[^0-9]/gi, "");
      window.pageConfig.raceid = raceid;
    }

    //清除邀请码
    window.localStorage.removeItem("invitationCode");
    window.localStorage.removeItem("invitationDiscount");
    window.localStorage.removeItem("invitationEventId");
    window.localStorage.removeItem("invitationEventName");
    window.localStorage.removeItem("invitationRaceId");

    // 判断环境

    if (
      navigator.userAgent.match(
        /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i
      )
    ) {
      window.localStorage.setItem("isPc", "false");
    } else {
      window.localStorage.setItem("isPc", "true");
    }

    //链接参数统一管理
    //_from
    if (!!this.$route.query._from) {
      cookie.set("_from", this.$route.query._from);
      //console.log(this.$route.query._from)
    }
    //_channel
    if (!!this.$route.query._channel) {
      cookie.set("_channel", this.$route.query._channel);
      //console.log(this.$route.query._from)
    }

    if (!!this.$route.query._sid) {
      //如果url能取到_sid
      cookie.set("_sid", this.$route.query._sid);
      //console.log(cookie.get("_sid"));
      window.localStorage.setItem("isLogin", true);
    }

    if (!!this.$route.query.openid) {
      window.localStorage.setItem("openid", this.$route.query.openid);
    }
    //console.log('-+')
    //console.log(!!cookie.get("_sid"));

    //设置报名
    window.localStorage.setItem("pageType", "baoming");
    //window.localStorage.setItem("pageType", "racelist");

    //window.localStorage.setItem("raceId", this.pageConfig.raceid);
    //console.log(window.localStorage.getItem('raceId'))

    window.getResponse = resp => {
      this._captcha_ = resp;
      console.log(resp);
    };

    if (location.href.indexOf("mode") != -1) {
      window.host = "http://v3.ihuipao.com/"; //测试
    } else {
      //window.host = "http://v3.ihuipao.com/";
      window.host = "//api.ihuipao.com/";
      //window.host = '//jiangtao.v3.ihuipao.com/'
      //window.host = "//wechat.ihuipao.com/"; //正式
    }

    //console.log(this.$route.query._sid)
    if (!!this.$route.query._sid) {
      //cookie.set("_sid", this.$route.query._sid);
      cookie.set("_sid", this.$route.query._sid);
    }

    //console.log(this)

    //h5 浏览器 mini 小程序 wx 微信
    var environment = hostoperating();
    hostoperating();

    var host = "https://ihuipao.cn/";
    var _sid = "";
    var base = new Base64();

    var url = base.encode(window.location.href);
    //var url = base.encode('https://r3.ihuipao.cn/wuxih5/baoming/dist/index.html#/list');
    var redirect = url;

    if (environment == "mini") {
    } else if (environment == "wx") {
      //

      //如果是在微信里面就 跳转授权
      if (!!cookie.get("_sid")) {
        //如果是登录状态
      } else {
        //this.wxlogin("auto");
        //如果是非登录状态
        //alert(`${host}auth/weixin/oauth?sid=${_sid}&redirect=${redirect}`)
        //alert(window.location.href)
        //window.location.href = `${host}auth/weixin/oauth?sid=${_sid}&redirect=${redirect}`;
        //return;
      }
      //'http://www.w3school.com.cn/My first/'
      //console.warn(`${host}auth/weixin/oauth?sid=${_sid}&redirect=${redirect}`)
      //alert(`${host}auth/weixin/oauth?sid=${_sid}&redirect=${redirect}`)
    } else {
    }

    this.isShow = true;

    this.pageType = window.localStorage.getItem("pageType");
    window.localStorage.setItem("isQuery", "true");

    this.host = host;

    /* console.log(location.href.indexOf('mode'))*/

    //window.host = 'http://v3.ihuipao.com/' //测试
  },
  mounted() {
    let _this = this;
    if (!!document.querySelector("#more")) {
      let more = document.querySelector("#more") || null;
      let moreP = more.querySelector("p") || null;
      let moreSpan = more.querySelector("span") || null;
      document.querySelector("body").addEventListener("click", function() {
        if (event.target == moreP || event.target == moreSpan) {
          console.log(event.target);
          return;
        } else {
          _this.close();
        }
      });
    }

    Bus.$on("showLogin", data => {
      //console.log(data);
      //展示
      this.$vux.toast.show({
        type: "text",
        width: "200px",
        time: "2000",
        text: `使用${data.msg}账号登录`,
        onHide() {
          _this.showToast = true;
          //_this.username = parseInt(data.msg);
        }
      });

      //console.log(data);
    });
  },
  methods: {
    codeChange() {
      LUOCAPTCHA.reset();
    },
    forget() {
      var _this = this;
      //找回密码
      this.axios
        .post(
          `${window.host}user/forgetpass`,
          qs.stringify({
            username: this.forusername,
            verify: this.code,
            passwd: this.forgetPsword
          })
        )
        .then(response => {
          if (response.data.code == "200") {
            //注册成功 存_sid
            this.$vux.toast.show({
              type: "success",
              text: "修改成功",
              onHide() {
                _this.mode = "";
              }
            });
          } else {
            this.$vux.toast.show({
              type: "warn",
              text: response.data.msg,
              onHide() {}
            });
          }
        });
    },
    reg() {
      this.axios
        .post(
          `${window.host}user/reg`,
          qs.stringify({
            username: this.username,
            verify: this.regCode,
            passwd: this.regPsword
          })
        )
        .then(response => {
          if (response.data.code == "200") {
            //注册成功 存_sid
            cookie.set("_sid", response.data.data._sid);

            this.showToast = false;
            this.$vux.toast.show({
              type: "success",
              text: "注册成功",
              onHide() {
                Bus.$emit("refresh");
              }
            });
          } else {
            this.$vux.toast.show({
              type: "warn",
              text: response.data.msg,
              onHide() {}
            });
          }
        });
    },
    sendCode(a) {
      var _this = this;
      var username = "";
      if (this.mode == "") {
        username = this.username;
      } else if (this.mode == "codelogin") {
        username = this.codeusername;
      } else if (this.mode == "pwd") {
        username = this.forusername;
      }

      this.axios
        .post(
          `${window.host}user/sms/send2`,
          qs.stringify({
            mobile: username,
            type: a,
            _captcha_: this._captcha_
          })
        )
        .then(response => {
          if (response.data.code == "200") {
            this.$vux.toast.show({
              type: "success",
              text: "验证码发送成功"
            });
            _this.clock = true;
            _this.codeMessage = countTime;
            let countDown = setInterval(function() {
              //console.log(_this.codeMessage)
              if (_this.codeMessage <= 1) {
                _this.codeMessage = "发送验证码";
                _this.clock = false;
                clearInterval(countDown);
                return;
              }
              _this.codeMessage--;
            }, 1000);
          } else {
            this.$vux.toast.show({
              type: "warn",
              text: response.data.msg
            });
          }
        });
    },
    show(a) {
      if (a == "wxlogin") {
        //微信登录去跳转
        this.wxlogin();
      }

      this.mode = a;
    },
    wxlogin(a) {
      //微信登录
      //获取_sid

      if (a == "auto" && !!cookie.get("_sid")) {
        return;
      }
      //alert('微信登录')

      var host = "https://ihuipao.cn/";
      var _sid = "";
      var base = new Base64();
      var url = base.encode(window.location.href);

      //var url = encodeURIComponent(window.location.href);
      //var url = base.encode('https://r3.ihuipao.cn/wuxih5/baoming/dist/index.html#/list');
      var redirect = url;

      this.axios.get(`${window.host}user/login/token`).then(response => {
        if (response.data.code == "200") {
          //微信登录跳转 获取_sid
          cookie.set("_sid", response.data.data._sid);
          //console.log(response.data.data._sid);
          //console.log(`${redirect}`)
          //alert(`${host}v3/auth/wechat?sid=${response.data.data._sid}&_r=${redirect}`)

          // alert(`${host}v3/auth/wechat?sid=${
          //   response.data.data._sid
          // }&_r=${redirect}`)

          window.location.href = `${host}v3/auth/wechat?sid=${
            response.data.data._sid
          }&_r=${redirect}`;

          //alert(`${host}v3/auth/wechat?sid=${response.data.data._sid}`);
          // window.location.href = `${host}v3/auth/wechat?sid=${
          //   response.data.data._sid
          // }`;
        } else {
          this.$vux.toast.show({
            type: "warn",
            text: response.data.msg
          });
        }
      });

      /*
      if (environment == "mini") {
      } else if (environment == "wx") {
        //如果是在微信里面就 跳转授权
        if (!!cookie.get("_sid")) {
          //如果是登录状态
        } else {
          //如果是非登录状态
          //alert(`${host}auth/weixin/oauth?sid=${_sid}&redirect=${redirect}`)
          window.location.href = `${host}auth/weixin/oauth?sid=${_sid}&redirect=${redirect}`;

          return;
        }
        //'http://www.w3school.com.cn/My first/'
        //console.warn(`${host}auth/weixin/oauth?sid=${_sid}&redirect=${redirect}`)
        //alert(`${host}auth/weixin/oauth?sid=${_sid}&redirect=${redirect}`)
      } else {
      }
      */
    },
    codelogin() {
      let _this = this;
      this.axios
        .post(
          `${window.host}user/auth`,
          qs.stringify({
            username: this.codeusername,
            code: this.code
          })
        )
        .then(response => {
          if (response.data.code == "200") {
            cookie.set("_sid", response.data.data._sid);
            Bus.$emit("refresh");
            this.$vux.toast.show({
              type: "success",
              text: "登录成功",
              onHide() {
                _this.showToast = false;
                //_this.$router.push({ path: "user" });
              }
            });
          } else {
            this.$vux.toast.show({
              type: "warn",
              text: response.data.msg
            });
          }
        });
    },
    login() {
      let _this = this;
      //cookie.remove("_sid");
      //console.log(host);
      this.axios
        .post(
          `${window.host}user/auth`,
          qs.stringify({
            username: this.username,
            passwd: this.loginPsword
          })
        )
        .then(response => {
          if (response.data.code == "200") {
            window.localStorage.setItem("isLogin", true);
            cookie.set("_sid", response.data.data._sid);
            this.$vux.toast.show({
              type: "success",
              text: "登录成功",
              onHide() {
                _this.showToast = false;
                Bus.$emit("refresh");
                //_this.$router.push({ path: "user" });
              }
            });
          } else {
            //this.showToast = false;
            this.$vux.toast.show({
              type: "warn",
              text: response.data.msg
            });
          }
        });
    },
    countDown(a) {
      if (this.clock) {
        return;
      }

      if (this.mode == "") {
        if (!isTel(this.username)) {
          this.$vux.toast.show({
            type: "warn",
            text: "请输入正确的手机号码"
          });
          return;
        }
      } else if (this.mode == "codelogin") {
        if (!isTel(this.codeusername)) {
          this.$vux.toast.show({
            type: "warn",
            text: "请输入正确的手机号码"
          });
          return;
        }
      } else if (this.mode == "pwd") {
        if (!isTel(this.forusername)) {
          this.$vux.toast.show({
            type: "warn",
            text: "请输入正确的手机号码"
          });
          return;
        }
      }

      if (!this._captcha_) {
        this.$vux.toast.show({
          type: "warn",
          text: "请先图形验证"
        });
        return;
      }

      // if (this.indexNumber == "") {
      //   return;
      // }
      // if (!isTel(this.tel)) {
      //   this.$vux.toast.show({
      //     type: "warn",
      //     text: "请输入正确的手机号码"
      //   });
      //   return;
      // }

      this.sendCode(a);
    },
    close() {
      Bus.$emit("close");
    },

    usernameChange(val) {
      //console.log(val)
      if (val == "" || val.type == "click") {
        return;
      }

      LUOCAPTCHA.reset();
      axios
        .post(`${window.host}user/isuser`, qs.stringify({ username: val }))
        .then(response => {
          if (response.data.code == "200") {
            if (response.data.data.length == 0) {
              //没有用户信息 走注册逻辑
              this.state = "reg";
            } else {
              //有用户信息 走登录逻辑
              this.state = "login";
            }
          } else {
            this.state = "";
            this.$vux.toast.show({
              type: "warn",
              text: response.data.msg
            });
          }
        });
      //输入姓名 触发登录操作
      //console.log(val);
    }
  },
  components: {
    CircleMenu1,
    Toast,
    myFooter,
    CircleMenu,
    XDialog,
    XButton,
    Group,
    Cell,
    XInput
  }
};
</script>

<style lang="less">
@import "../src/common/css/index.less";
@import "~vux/src/styles/close";
#app {
  position: relative;
}

body {
  background-color: #fbf9fe;
  max-width: 850px;
  margin: 0 auto;
  touch-action: none;
}

#showlogin .vux-x-input {
  background: none;
}

.dialog-demo {
  .weui-dialog {
    border-radius: 8px;
    padding-bottom: 8px;
  }
  .dialog-title {
    line-height: 30px;
    color: #666;
  }
  .img-box {
    height: 350px;
    overflow: hidden;
  }
  .vux-close {
    margin-top: 8px;
    margin-bottom: 8px;
  }
}

body.vux-modal-open {
  position: static;
  max-width: 850px;
}

body .weui-btn_mini {
}

.icons {
  padding-top: 20px;
  span {
    width: 45%;
    font-size: 15px;
    display: inline-block;
    font-size: 15px;
    i {
      padding-right: 5px;
    }
  }
}

#showlogin .vux-x-dialog .vux-x-input input {
  border: 0;
  width: 100%;
}

.rightbottom-button {
  background: #ed5863;
  height: 50px;
  width: 100px;
  text-align: center;
  position: relative;
  top: -14px;
  right: -20px;
  line-height: 50px;
  font-size: 17px;
}
</style>
